<?php
class Model_User_ActivationCode extends Forum_Db_Table
{
    protected $_name = 'user_activation_code';
    
    protected $_primary = 'id'; 
    
    /**
     * Create activation row
     * 
     * @param int $user_id
     * @param string $type(register|forgot_password)
     * @return int id of created row
     */
    public function create($user_id = null, $type = 'register')
    {
        $date = date('Y-m-d H:i:s');
        $date_expire = date('Y-m-d H:i:s', time() + (24 * 60 * 60)); // one day
        
        return $this->getAdapter()->insert($this->_name, array(
            'user_id' => $user_id,
            'code' => $this->_generateHash(),
            'type' => $type,
            'created_on' => $date,
            'expire_on' => $date_expire,
            'status' => 'queued'
        ));
    }
    
    /**
     * Delete activation row
     * 
     * @param int $user_id
     * @param string $code
     * @return bool
     */
    public function delete($user_id = null, $code = '', $type = 'register')
    {
        return $this->getAdapter()->delete(
            $this->_name, 
            array(
                "code = '{$code}'", 
                "user_id = '{$user_id}'",
                "type = '{$type}'"
            )
        );
    }
    
    /**
     * Update status of activation code
     * 
     * @param int $id
     * @param string(queued|sended|error) $status
     * @return unknown_type
     */
    public function setStatus($id, $status = '')
    {
        return $this->getAdapter()->update(
            $this->_name,
            array(
                'status' => $status
            ),
            "id = {$id}"
        );
    }

    /**
     * Validates activation request
     * 
     * @param int $user_id
     * @param string $code
     * @param string $type(register|forgot_password)
     * @return bool
     */
    public function validate($user_id = null, $code = '', $type = 'register')
    {
        $query = "SELECT * 
            FROM {$this->_name}
            WHERE user_id = '{$user_id}'
            AND code = '{$code}'
            AND type = '{$type}'";
        
        if ($row = $this->getAdapter()->fetchRow($query)) {
            $date = date('Y-m-d H:i:s');
            if ($row['expire_on'] < $date) {
                $this->delete($user_id, $code, $type);
            } else {
                return true;
            }
        }
        
        $activation_url = Forum_Helper_Url::getInstance()->getUrl('account/activate');
            Forum_Message::getInstance()
                ->addError("Код активації для вказаного користувача не знайдений, або є невірним")
                ->addError("Ви можете спробувати створити його тут:
                    <a href='{$activation_url}' title='{$activation_url}'>{$activation_url}</a>");
        
        return false;
    }
    
    /**
     * Generates md5 hash string
     * 
     * @return string
     */
    protected function _generateHash() 
    {
        mt_srand((double)microtime(1)*1000000);
        return md5(mt_rand());
    }
    
}